<template>
  <div ref="chartRef" class="chart-container"></div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts'
import type { ECharts, EChartsOption } from 'echarts'

const props = defineProps<{
  data: {
    labels: string[]
    datasets: Array<{
      name: string
      values: number[]
      color?: string
    }>
  }
}>()

const chartRef = ref<HTMLElement>()
let chart: ECharts | null = null

const initChart = () => {
  if (!chartRef.value) return
  
  chart = echarts.init(chartRef.value)
  updateChart()
  
  window.addEventListener('resize', handleResize)
}

const updateChart = () => {
  if (!chart) return

  const option: EChartsOption = {
    tooltip: {
      trigger: 'axis'
    },
    legend: {
      data: props.data.datasets.map(d => d.name)
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      containLabel: true
    },
    xAxis: {
      type: 'category',
      boundaryGap: false,
      data: props.data.labels
    },
    yAxis: {
      type: 'value'
    },
    series: props.data.datasets.map(dataset => ({
      name: dataset.name,
      type: 'line',
      data: dataset.values,
      itemStyle: {
        color: dataset.color
      },
      smooth: true,
      symbol: 'circle',
      symbolSize: 8,
      lineStyle: {
        width: 3
      }
    }))
  }

  chart.setOption(option)
}

const handleResize = () => {
  chart?.resize()
}

onMounted(initChart)
onBeforeUnmount(() => {
  window.removeEventListener('resize', handleResize)
  chart?.dispose()
})

watch(() => props.data, updateChart, { deep: true })
</script>

<style scoped>
.chart-container {
  width: 100%;
  height: 400px;
}
</style>
